// 引入Vue
import Vue from 'vue'

//引入VueRouter
import VueRouter from 'vue-router'
// 引入路由规则
import routes from './routes'
import {getToken} from '../utils/auth'
//应用VueRouter
Vue.use(VueRouter)

//第一步：将VueRouter原型对象上的push缓存一份
const originPush = VueRouter.prototype.push
//第一步：将VueRouter原型对象上的replace缓存一份
const originReplace = VueRouter.prototype.replace

//第二步：增强push
VueRouter.prototype.push = function(location,okCallback,errCallback){
	//如果程序员调用this.$router.push的时候，只传了跳转的位置
	if(okCallback === undefined && errCallback === undefined){
		return originPush.call(this,location).catch(()=>{})
	}else{
		return originPush.call(this,location,okCallback,errCallback)
	}
}
//第二步：增强replace
VueRouter.prototype.replace = function(location,okCallback,errCallback){
	//如果程序员调用this.$router.push的时候，只传了跳转的位置
	if(okCallback === undefined && errCallback === undefined){
		return originReplace.call(this,location).catch(()=>{})
	}else{
		return originReplace.call(this,location,okCallback,errCallback)
	}
}

// 创建一个路由器
const router= new VueRouter({
	mode:'history',
	routes,
	scrollBehavior (to, from, savedPosition) {
		if (savedPosition) {
			return savedPosition
		  } else {
			return { x: 0, y: 0}
		  }
	  }
})

const authPath = ['/pay','/order','trade']
router.beforeEach((to,from,next)=>{
	const token = getToken()
	const userInfo = JSON.parse(localStorage.getItem('userInfo'))
	if(token){
		if(userInfo){
			next()
		}else{
			authPath.indexOf(to.path) !== -1 ? next('/login') : next()
		}
	}else{
		//你肯定没登录
		if(authPath.indexOf(to.path) !== -1){
			next('/login')
		}else{
			next()
		}
	}
})
export default router



